package messagesvc.executor.record;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.ucloud.microsf.commonlib.CommonContext;
import cn.ucloud.microsf.commonlib.response.EmptyResponse;
import cn.ucloud.microsf.commonlib.util.Utils;
import cn.ucloud.microsf.messagesvc.biz.MessageFormatter;
import cn.ucloud.microsf.messagesvc.biz.SubscribeService;
import cn.ucloud.microsf.messagesvc.biz.impl.DefaultMessageFormatter;
import cn.ucloud.microsf.messagesvc.orm.entity.RecordEntity;
import cn.ucloud.microsf.messagesvc.orm.entity.TemplateEntity;
import cn.ucloud.microsf.messagesvc.orm.mapper.RecordMapper;
import cn.ucloud.microsf.messagesvc.orm.mapper.TemplateMapper;
import cn.ucloud.microsf.messagesvc.orm.model.SubscribeDO;
import cn.ucloud.microsf.messagesvc.request.record.SendRequest;
import cn.ucloud.microsf.messagesvc.websocket.service.WsService;
import cn.ucloud.microsf.mpcsvc.common.enums.SendStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class MessageSendExecutor {

  @Autowired
  private WsService wsService;
  @Autowired
  private TemplateMapper templateMapper;
  @Autowired
  private RecordMapper recordMapper;
  @Autowired
  private SubscribeService subscribeService;

  @Transactional
  public EmptyResponse execute(SendRequest request) {

    String content = request.getContent();
    String senderId = CommonContext.getUserUuid();
    String senderName = CommonContext.getUserName();
    if (StrUtil.isNotBlank(request.getTemplate())) {
      TemplateEntity template = getTemplate(request.getTemplate());
      content = template.getContent();
      if (request.isWide() && template.getIsWide()){
        List<SubscribeDO> subTemps = subscribeService.getByTempCode(template.getCode());
        if (CollectionUtil.isNotEmpty(subTemps)){
          request.setReceiver(subTemps.stream().map(SubscribeDO::getSubId).collect(Collectors.toList()));
        }
      }

      // TODO 获取发送人配置

    }
    // 格式化消息
    MessageFormatter formatter = new DefaultMessageFormatter();
    content = formatter.format(content, request.getParams());

    // 接收人
    for (String receiver : request.getReceiver()) {
      RecordEntity recordEntity = new RecordEntity();
      recordEntity.setUuid(Utils.generateUUID());
      recordEntity.setSenderId(senderId);
      recordEntity.setSenderName(senderName);
      recordEntity.setContent(content);
      recordEntity.setReceiverId(receiver);
      recordEntity.setReceiverName(receiver);
      recordEntity.setIsRead(false);
      recordEntity.setStatus(SendStatus.NONE);

      boolean success = wsService.sendByQueue(receiver, recordEntity.getContent());

      SendStatus sendStatus = success ? SendStatus.SUCCESS : SendStatus.FAIL;
      recordEntity.setStatus(sendStatus);
      recordMapper.insert(recordEntity);
    }
    return EmptyResponse.builder().build();
  }


  private TemplateEntity getTemplate(String code) {
    QueryWrapper<TemplateEntity> wrapper = new QueryWrapper<>();
    wrapper.eq("`code`", code);
    wrapper.eq("is_delete", false);
    return templateMapper.selectOne(wrapper);

  }
}
